package cn.com.iscs.sqlProject.Intercepts;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.DateFormat;
import java.util.*;

import static cn.com.iscs.sqlProject.constants.Constants.THREAD_LOCAL;

/**
 * Created by yejunjun on 2017/3/2.
 */
@Intercepts(value = {
		@Signature(type = Executor.class,
				method = "update",
				args = {MappedStatement.class, Object.class})})
public class MybatisInterceptor implements Interceptor {

	private static List<String> interceptorSqlId = new ArrayList<>();

	private Logger logger = LoggerFactory.getLogger(MybatisInterceptor.class);

	private Properties properties;
	static {
		interceptorSqlId.add("cn.com.iscs.sqlProject.mapper.CfOperationUnitMapper.insert");
		interceptorSqlId.add("cn.com.iscs.sqlProject.mapper.AuOperationFunctionMapper.insert");
		interceptorSqlId.add("cn.com.iscs.sqlProject.mapper.CfOperationRouteMapper.insert");
		interceptorSqlId.add("cn.com.iscs.sqlProject.mapper.AuBusinessRelationMapper.insert");
		interceptorSqlId.add("cn.com.iscs.sqlProject.mapper.CfCardLabelMapper.insert");
	}

	public Object intercept(Invocation invocation) throws Throwable {
		MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
		Object parameter = null;
		if (invocation.getArgs().length > 1) {
			parameter = invocation.getArgs()[1];
		}
		String sqlId = mappedStatement.getId();
		if(interceptorSqlId.contains(sqlId)){
			BoundSql boundSql = mappedStatement.getBoundSql(parameter);
			Configuration configuration = mappedStatement.getConfiguration();
			String sql = showSql(configuration, boundSql);
			logger.info("打印的sql----------------------： " + sql);
			List<String> sqls = THREAD_LOCAL.get();
			if (sqls == null) {
				sqls = new ArrayList<>();
			}
			sqls.add(sql);
			THREAD_LOCAL.set(sqls);
		}
		Object returnValue = invocation.proceed();
		return returnValue;
	}


	private static String getParameterValue(Object obj) {
		String value = null;
		if (obj instanceof String) {
			value = "'" + obj.toString() + "'";
		} else if (obj instanceof Date) {
			DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
			value = "'" + formatter.format(new Date()) + "'";
		} else {
			if (obj != null) {
				value = obj.toString();
			} else {
				value = "null";
			}

		}
		return value;
	}

	public static String showSql(Configuration configuration, BoundSql boundSql) {
		Object parameterObject = boundSql.getParameterObject();
		List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
		String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
		if (parameterMappings.size() > 0 && parameterObject != null) {
			TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
			if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
				sql = sql.replaceFirst("\\?", getParameterValue(parameterObject));

			} else {
				MetaObject metaObject = configuration.newMetaObject(parameterObject);
				for (ParameterMapping parameterMapping : parameterMappings) {
					String propertyName = parameterMapping.getProperty();
					if (metaObject.hasGetter(propertyName)) {
						Object obj = metaObject.getValue(propertyName);
						sql = sql.replaceFirst("\\?", getParameterValue(obj));
					} else if (boundSql.hasAdditionalParameter(propertyName)) {
						Object obj = boundSql.getAdditionalParameter(propertyName);
						sql = sql.replaceFirst("\\?", getParameterValue(obj));
					}
				}
			}
		}
		return sql+";";
	}

	public Object plugin(Object target) {
		return Plugin.wrap(target, this);
	}

	public void setProperties(Properties properties0) {
		this.properties = properties0;
	}
}
